package com.example.studentmanagement2.controller;

import com.example.studentmanagement2.model.User;
import com.example.studentmanagement2.repository.Repository.UserRepository;
import com.example.studentmanagement2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        return ResponseEntity.ok(userService.getAllUsers());
    }

    @PostMapping
    public ResponseEntity<User> addUser(@RequestBody User user) {
        return new ResponseEntity<>(userService.addUser(user), HttpStatus.CREATED);
    }

    @PutMapping("/{originalId}")  // 路径参数为原始学号
    public ResponseEntity<User> updateUser(
            @PathVariable String originalId,  // 原始学号
            @RequestBody User user      // 包含新学号的请求体
    ) {
        return ResponseEntity.ok(userService.updateUser(originalId, user));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable String id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable String id) {
        Optional<User> user = userService.getUserById(id);  // 正确调用服务层方法
        return user.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @GetMapping("/search")
    public ResponseEntity<List<User>> searchUsers(
            @RequestParam(required = false) String keyword
    ) {
        List<User> users = userService.searchUsers(keyword);
        return ResponseEntity.ok(users);
    }



}
